package com.dd.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.dd.model.AQIData;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.io.InputStreamReader;
import java.io.InputStream;

public class AQIDataService {
    private static final String DATA_FILE = "/aqi_data.json";

    private Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .excludeFieldsWithoutExposeAnnotation()
            .create();

    public List<AQIData> getAllAQIData() {
        InputStream is = getClass().getResourceAsStream("/aqi_data.json");
        if (is == null) {
            System.err.println("找不到资源文件: " + DATA_FILE);
            throw new RuntimeException("找不到资源文件: " + DATA_FILE);
        }
        try (InputStreamReader reader = new InputStreamReader(is, "UTF-8")) {
            Type listType = new TypeToken<ArrayList<AQIData>>() {}.getType();
            List<AQIData> data = gson.fromJson(reader, listType);
            return data != null ? data : new ArrayList<>();
        } catch (IOException e) {
            System.err.println("Error reading AQI data file or file not found: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    public void saveAllAQIData(List<AQIData> data) {
        try (FileWriter writer = new FileWriter(DATA_FILE)) {
            gson.toJson(data, writer);
        } catch (IOException e) {
            System.err.println("Error writing AQI data to file: " + e.getMessage());
        }
    }

 
}
